<template>
  <div class="bind-phone-container">
    <div class="bind-phone-box">
      <div class="bind-phone-header">
        <h2>绑定手机号</h2>
        <p>请绑定手机号完成QQ登录</p>
      </div>
      
      <el-form 
        ref="bindFormRef" 
        :model="bindForm" 
        :rules="bindRules" 
        label-width="0"
        class="bind-phone-form"
      >
        <!-- 手机号输入 -->
        <el-form-item prop="phone">
          <el-input
            v-model="bindForm.phone"
            placeholder="请输入手机号"
            prefix-icon="Phone"
            clearable
            @input="handlePhoneInput"
          />
        </el-form-item>

        <!-- 图片验证码 -->
        <el-form-item prop="imageCode">
          <div class="captcha-container">
            <el-input
              v-model="bindForm.imageCode"
              placeholder="请输入图片验证码"
              prefix-icon="Picture"
              clearable
              style="flex: 1; margin-right: 10px;"
            />
            <div class="captcha-image" @click="refreshCaptcha">
              <img 
                v-if="captchaUrl" 
                :src="captchaUrl" 
                alt="验证码"
                style="width: 100%; height: 100%; cursor: pointer;"
              />
              <div v-else class="captcha-loading">
                <el-icon><Loading /></el-icon>
              </div>
            </div>
          </div>
        </el-form-item>

        <!-- 发送短信按钮 -->
        <el-form-item>
          <el-button 
            type="primary" 
            :loading="sendingSMS"
            :disabled="!canSendSMS"
            @click="sendSMS"
            style="width: 100%;"
          >
            {{ sendButtonText }}
          </el-button>
        </el-form-item>

        <!-- 短信验证码 -->
        <el-form-item prop="smsCode">
          <el-input
            v-model="bindForm.smsCode"
            placeholder="请输入短信验证码"
            prefix-icon="Message"
            clearable
            maxlength="4"
            show-word-limit
          />
        </el-form-item>

        <!-- 绑定按钮 -->
        <el-form-item>
          <el-button 
            type="success" 
            :loading="binding"
            :disabled="!canBind"
            @click="handleBind"
            style="width: 100%;"
          >
            绑定手机号
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 倒计时显示 -->
      <div v-if="countdown > 0" class="countdown">
        <el-text type="info">{{ countdown }}秒后可重新发送</el-text>
      </div>

      <!-- 返回登录页 -->
      <div class="back-to-login">
        <el-button 
          type="text" 
          @click="backToLogin"
          style="color: #409eff;"
        >
          返回登录页
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Phone, Picture, Message, Loading } from '@element-plus/icons-vue'
import { authAPI } from '@/api/index'

const router = useRouter()

// 表单引用
const bindFormRef = ref()

// 表单数据
const bindForm = reactive({
  phone: '',
  imageCode: '',
  smsCode: '',
  uuid: ''
})

// 表单验证规则
const bindRules = {
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
  ],
  imageCode: [
    { required: true, message: '请输入图片验证码', trigger: 'blur' },
    { min: 4, max: 4, message: '验证码长度为4位', trigger: 'blur' }
  ],
  smsCode: [
    { required: true, message: '请输入短信验证码', trigger: 'blur' },
    { min: 4, max: 4, message: '验证码长度为4位', trigger: 'blur' }
  ]
}

// 状态变量
const captchaUrl = ref('')
const sendingSMS = ref(false)
const binding = ref(false)
const countdown = ref(0)
const countdownTimer = ref(null)

// 计算属性
const canSendSMS = computed(() => {
  return bindForm.phone && bindForm.imageCode && countdown.value === 0
})

const canBind = computed(() => {
  return bindForm.phone && bindForm.smsCode
})

const sendButtonText = computed(() => {
  if (sendingSMS.value) return '发送中...'
  if (countdown.value > 0) return `${countdown.value}s后重发`
  return '发送短信验证码'
})

// 生成UUID
const generateUUID = () => {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
    const r = Math.random() * 16 | 0
    const v = c === 'x' ? r : (r & 0x3 | 0x8)
    return v.toString(16)
  })
}

// 刷新图片验证码
const refreshCaptcha = () => {
  bindForm.uuid = generateUUID()
  captchaUrl.value = authAPI.getImageCode(bindForm.uuid) + '&t=' + Date.now()
}

// 手机号输入处理
const handlePhoneInput = () => {
  // 只允许输入数字
  bindForm.phone = bindForm.phone.replace(/\D/g, '')
  // 限制长度为11位
  if (bindForm.phone.length > 11) {
    bindForm.phone = bindForm.phone.slice(0, 11)
  }
}

// 发送短信验证码
const sendSMS = async () => {
  if (!canSendSMS.value) return

  try {
    sendingSMS.value = true
    
    const response = await authAPI.sendSMS({
      phone: bindForm.phone,
      code: bindForm.imageCode,
      uuid: bindForm.uuid
    })

    if (response.success) {
      ElMessage.success('短信验证码发送成功')
      startCountdown()
    } else {
      ElMessage.error(response.message || '发送失败')
    }
  } catch (error) {
    console.error('发送短信失败:', error)
  } finally {
    sendingSMS.value = false
  }
}

// 开始倒计时
const startCountdown = () => {
  countdown.value = 60
  countdownTimer.value = setInterval(() => {
    countdown.value--
    if (countdown.value <= 0) {
      clearInterval(countdownTimer.value)
      countdownTimer.value = null
    }
  }, 1000)
}

// 绑定手机号处理
const handleBind = async () => {
  if (!canBind.value) return

  try {
    await bindFormRef.value.validate()
    
    binding.value = true
    
    // 获取QQ登录信息
    const openid = localStorage.getItem('qq_openid')
    if (!openid) {
      ElMessage.error('QQ登录信息已失效，请重新登录')
      router.push('/login')
      return
    }

    const response = await authAPI.bindPhone({
      openid: openid,
      phone: bindForm.phone,
      sms_code: bindForm.smsCode
    })

    if (response.success) {
      // 绑定成功，保存token和用户信息到localStorage
      localStorage.setItem('token', response.data.token)
      localStorage.setItem('retoken', response.data.retoken)
      localStorage.setItem('userInfo', JSON.stringify({
        user_id: response.data.user_id,
        phone: response.data.phone,
        username: response.data.username
      }))

      // 清除临时存储的QQ信息
      localStorage.removeItem('qq_openid')
      localStorage.removeItem('qq_user_info')

      ElMessage.success('手机号绑定成功')
      
      // 跳转到首页
      router.push('/')
    } else {
      ElMessage.error(response.message || '绑定失败')
    }
  } catch (error) {
    console.error('绑定失败:', error)
  } finally {
    binding.value = false
  }
}

// 返回登录页
const backToLogin = () => {
  // 清除临时存储的QQ信息
  localStorage.removeItem('qq_openid')
  localStorage.removeItem('qq_user_info')
  router.push('/login')
}

// 组件挂载时初始化
onMounted(() => {
  // 检查是否有QQ登录信息
  const openid = localStorage.getItem('qq_openid')
  if (!openid) {
    ElMessage.error('QQ登录信息已失效，请重新登录')
    router.push('/login')
    return
  }
  
  refreshCaptcha()
})

// 组件卸载时清理定时器
onUnmounted(() => {
  if (countdownTimer.value) {
    clearInterval(countdownTimer.value)
  }
})
</script>

<style scoped>
.bind-phone-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
}

.bind-phone-box {
  width: 100%;
  max-width: 400px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  padding: 40px;
}

.bind-phone-header {
  text-align: center;
  margin-bottom: 30px;
}

.bind-phone-header h2 {
  color: #333;
  margin-bottom: 8px;
  font-size: 24px;
}

.bind-phone-header p {
  color: #666;
  font-size: 14px;
  margin: 0;
}

.bind-phone-form {
  margin-bottom: 20px;
}

.captcha-container {
  display: flex;
  align-items: center;
  gap: 10px;
}

.captcha-image {
  width: 100px;
  height: 40px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f7fa;
}

.captcha-loading {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  color: #909399;
}

.countdown {
  text-align: center;
  margin-top: 10px;
}

.back-to-login {
  text-align: center;
  margin-top: 20px;
}

/* 响应式设计 */
@media (max-width: 480px) {
  .bind-phone-box {
    padding: 20px;
  }
  
  .captcha-image {
    width: 80px;
  }
}
</style>
